<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #canvas{
            display: block;
            margin: 50px auto;
            border: 1px solid #000000;
            background: white;
        }
    </style>
</head>
<body>
    <canvas id="canvas" width="600" height="400">
        该浏览器不支持canvas
    </canvas>
    <input type="button" value="在页面生成图片" id="newimg">
</body>
<script>
    let canvas = document.getElementById('canvas')
    let context = canvas.getContext('2d')
    let title = '文本换行'
    let text = 'I like to listen to all kinds of music, music makes me happy,' +
        ' when I feel sad, I will listen to music and it relieves me. My favorite ' +
        'song is Never Say Never, the words are so inspiring. The song tells people' +
        ' never to give up, no matter what happens.The song inspires me to move on and' +
        ' get over all kinds of difficulties.'
    let textArr = text.split(" ")
    let maxWidth = 300
    let lineHeight = 30
    let startX = (canvas.width - maxWidth)/2
    let startY = 50
    context.font="16px Arial"

    //绘制标题
    context.fillText(title,(canvas.width - context.measureText(title).width)/2,20)
    let line=""
    //循环数组
    for (let i=0;i<textArr.length;i++){
        let testLine = line + textArr[i] + " "
        let metrics = context.measureText(testLine)//测量文本
        if (metrics.width > maxWidth){//如果长度大于最宽
            context.fillText(line,startX,startY)
            line = textArr[i] + " "
            startY += lineHeight
        } else{
            line = testLine
        }
    }
    context.fillText(line,startX,startY)


    //把canvas转换成Blob
    canvas.toBlob(function(blob){
        console.log(blob);
        let reader=new FileReader();
        reader.readAsDataURL(blob,'utf-8');
        console.log(blob)
        reader.onload=function(e) {
            console.log(this.result);
            let a = document.createElement("a");
            a.innerHTML = "点击下载";
            a.href = window.URL.createObjectURL(blob);
            document.body.appendChild(a);
            a.onclick = function () {
                a.download = 'canvas.png';//下载文件，doc文件
            }
        }
        ///点击生成一张图片
             newimg.onclick=function () {
                 let img=document.createElement("img");
                 img.src=window.URL.createObjectURL(blob);
                 document.body.appendChild(img);
             }
    })

</script>
</html>